<?php
// $Id: uc_deliverytimeslot.admin.inc,v 1.2.2.1 2009/12/01 16:46:32 mogtofu33 Exp $

/**
 * @file
 * Delivery time slot administration menu items and settings.
 *
 */

/**
 * Display the delivery timeslot view.
 */
function uc_deliverytimeslot_view() {

  $sign_flag = variable_get('uc_sign_after_amount', FALSE);
  $currency_sign = variable_get('uc_currency_sign', '$');

  if (isset($_POST['filter_status'])) {
    $_SESSION['filter_status'] = $_POST['filter_status'];
    $status = $_POST['filter_status'];
  }
  else {
    if (isset($_SESSION['filter_status'])) {
      $status = $_SESSION['filter_status'];
    }
    else {
      $status = 1;
    }
  }

  if ($_POST['start_date']) {
    $_SESSION['start_date'] = $_POST['start_date'];
    $_SESSION['end_date'] = $_POST['end_date'];
    $start_date = _uc_deliverytimeslot_date($_POST['start_date']);
    $end_date = _uc_deliverytimeslot_date($_POST['end_date']);
  }
  else {
    if (isset($_SESSION['start_date']) && !is_null($_SESSION['start_date'])) {
      $start_date = _uc_deliverytimeslot_date($_SESSION['start_date']);
      $end_date = _uc_deliverytimeslot_date($_SESSION['end_date']);
    }
    else {
      $start_date = _uc_deliverytimeslot_date(FALSE);
      $end_date = _uc_deliverytimeslot_date(FALSE, 10);
    }
  }

  $filter = '<div class="uc-deliverytimeslot-filter-form">'. drupal_get_form('uc_deliverytimeslot_view_filter') .'</div>';
  $filter .= '<div class="uc-deliverytimeslot-filter-date-form">'. drupal_get_form('uc_deliverytimeslot_view_date') .'</div>';

  $timeslot = _uc_deliverytimeslot_timeslot();
  $sql = "SELECT order_id, date, sid FROM {uc_deliverytimeslot_order} ".
         "WHERE date >= '%s' AND date <= '%s' AND confirmed = %d ".
         "ORDER BY date ASC, sid ASC";
  $req = db_query($sql, $start_date, $end_date, (int)$status);
  while ($res = db_fetch_array($req)) {
    $order = uc_order_load($res['order_id']);
    $product_listing = '';
    foreach ($order->products as $product) {
      $product_listing .=  $product->qty .'x '. $product->title .'<br/>';
      if (is_array($product->data['attributes']) && count($product->data['attributes']) > 0) {
        $product_listing .= '<ul class="product-description">';
        foreach ($product->data['attributes'] as $attribute => $option) {
        $product_listing .= '<li>'. t('@attribute: @options', array('@attribute' => $attribute, '@options' => implode(', ', (array)$option))) .'</li>';
        }
        $product_listing .= '</ul>';
        }
    }
    $product_listing .= t("Total order #!orderid:", array('!orderid' => l($order->order_id, 'admin/store/orders/'. $order->order_id))) .' ';
    $sign_flag ? '' : $product_listing .= $currency_sign;
    $product_listing .= uc_order_get_total($order);
    $sign_flag ? $product_listing .= $currency_sign : '';
    $ship_information = uc_order_address($order, 'delivery') .'<br />'. check_plain($order->delivery_phone);
    $date = uc_date_format(date('Y', $res['date']), date('m', $res['date']), date('d', $res['date']));
    $row = array($date, $timeslot[$res['sid']], $ship_information, $product_listing);
    $rows[] = $row;
    $main_rows[] = array_merge($row, array(uc_order_actions($order, TRUE)));
  }
  $header = array(t('Date'), t('Timeslot'), t('Delivery'), t('Order'));
  $main_header = array_merge($header, array(t('Operations')));

  if (arg(4) && arg(4) == 'print') {
    print theme('table', $header, $rows);
    exit();
  }
  $output = $filter . theme('table', $main_header, $main_rows, array('class' => 'uc-deliverytimeslot-table order-pane-table'));
  $icon = '<img src="'. base_path() . drupal_get_path('module', 'uc_deliverytimeslot') .'/images/print_icon.gif" />';
  $output .= l($icon . t('Printable delivery timeslot'), 'admin/store/orders/deliverytimeslot/print', array('html' => TRUE));

  return $output;
}

/**
 * @see uc_deliverytimeslot_view()
 */
function uc_deliverytimeslot_view_filter() {
  $options = array(1 => t('Confirmed'), 0 => t('Unconfirmed'));

  if (!isset($_SESSION['filter_status'])) {
    $default_status = 1;
  }
  else {
    $default_status = $_SESSION['filter_status'];
  }

  $form['filter_status'] = array(
    '#type' => 'select',
    '#title' => t('Filter by status'),
    '#options' => $options,
    '#default_value' => $default_status,
    '#attributes' => array('onchange' => 'this.form.submit();')
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'View',
    '#attributes' => array('style' => 'display: none;')
  );

  return $form;
}

/**
 * @see uc_deliverytimeslot_view()
 */
function uc_deliverytimeslot_view_date() {

  if (isset($_SESSION['start_date']) && isset($_SESSION['end_date'])) {
    $start_date = _uc_deliverytimeslot_date($_SESSION['start_date']);
    $end_date = _uc_deliverytimeslot_date($_SESSION['end_date']);
  }
  else {
    $start_date = _uc_deliverytimeslot_date(FALSE);
    $end_date = _uc_deliverytimeslot_date(FALSE, 10);
  }

  $form['date']= array(
    '#type' => 'fieldset',
    '#title' => t('Date range selection'),
    '#collapsible' => TRUE,
    '#collapsed' => isset($_SESSION['start_date']) ? FALSE : TRUE,
  );
  $form['date']['start_date'] = array(
    '#type' => 'date',
    '#title' => t('Start date'),
    '#prefix' => '<div style="display:block;float:left;margin-right:15px;">',
    '#suffix' => '</div>',
    '#default_value' => array(
      'month' => date("n", $start_date),
      'day' => date("j", $start_date),
      'year' => date("Y", $start_date),
    ),
  );
  $form['date']['end_date'] = array(
    '#type' => 'date',
    '#title' => t('End date'),
    '#prefix' => '<div style="display:block;float:left;">',
    '#suffix' => '</div>',
    '#default_value' => array(
      'month' => date("n", $end_date),
      'day' => date("j", $end_date),
      'year' => date("Y", $end_date),
    ),
  );
  $form['date']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#prefix' => '<br style="clear:both;"/>',
  );

  return $form;
}

/**
 * @see uc_deliverytimeslot_view()
 */
function uc_deliverytimeslot_view_date_validate($form, &$form_state) {
  if (isset($form_state['values']['start_date']) && isset($form_state['values']['start_date'])) {
    $start_date = _uc_deliverytimeslot_date($form_state['values']['start_date']);
    $end_date = _uc_deliverytimeslot_date($form_state['values']['end_date']);
    if ($end_date < $start_date) {
      form_set_error('end_date', t('End date need to be next or equal to start date.'));
    }
  }

}

/**
 * Delivery time slot configuration.
 *
 * @ingroup forms
 * @see uc_deliverytimeslot_admin_view_filter()
 *
 */
function uc_deliverytimeslot_admin_view() {

  drupal_add_css(drupal_get_path('module', 'uc_deliverytimeslot') .'/uc_deliverytimeslot_default.css');
  $output = '';
  $rows = array();
  $week_days = _uc_deliverytimeslot_week_days();
  $timeslot = $time_slot= _uc_deliverytimeslot_timeslot();

  // settings
  $output .= '<div class="uc-deliverytimeslot-settings-form">'. drupal_get_form('uc_deliverytimeslot_settings') .'</div>';
  // generate
  $output .= '<div class="uc-deliverytimeslot-generate-form">'. drupal_get_form('uc_deliverytimeslot_settings_generate') .'</div>';

  if ($_POST['filter_day']) {
    $_SESSION['filter_day'] = $_POST['filter_day'];
    $day = $_POST['filter_day'];
  }
  else {
    if (isset($_SESSION['filter_day']) && !is_null($_SESSION['filter_day'])) {
      $day = $_SESSION['filter_day'];
    }
    else {
      $day = key(variable_get('uc_deliverytimeslot_week_days', _uc_deliverytimeslot_week_days()));
    }
  }

  // default time slot table
  $req = db_query("SELECT ddid, sid, max_limit FROM {uc_deliverytimeslot_default}
                   WHERE uc_deliverytimeslot_default.day = '%s'
                   ORDER BY uc_deliverytimeslot_default.sid", $day);

  while ($res = db_fetch_object($req)) {
    $row = array();
    $row[] = check_plain($timeslot[$res->sid]);
    $row[] = $res->max_limit;
    $row[] = l(t('edit'), 'admin/store/settings/deliverytimeslot/admin/default/'. $res->ddid);
    $rows[] = $row;

  }
  // filter by day
  $output .= '<div class="uc-deliverytimeslot-default">';
  $output .= '<div class="uc-deliverytimeslot-filter-form">'. drupal_get_form('uc_deliverytimeslot_admin_view_filter') .'</div>';

  if (count($rows)) {
    $header = array(t('Time slot'), t('Max limit'), t('Operations'));
    $output .= theme('table', $header, $rows, array(), t('Default delivery time slot table for !day', array('!day' => $day)));
  }
  else {
    $output .= t('No default time slot table for this day.') .'&nbsp;';
  }

  // add timeslot
  $existing_slot_query = db_query("SELECT sid FROM {uc_deliverytimeslot_default} WHERE day = '%s'", $day);
  while ($existing_slot_res = db_fetch_array($existing_slot_query)) {
    unset($time_slot[$existing_slot_res['sid']]);
  }
  if (count($time_slot) > 0) {
    $output .= l(t('Add timeslot for !day', array('!day' => $day)), 'admin/store/settings/deliverytimeslot/admin/default/add/'. $day);
  }
  else {
    $output .= t('All timeslot for !day used.', array('!day' => $day));
  }
  $output .= '</div>';

  // special table time
  $req = db_query('SELECT * FROM {uc_deliverytimeslot_special} ORDER BY uc_deliverytimeslot_special.date');
  $rows = array();
  while ($res = db_fetch_object($req)) {
    $row = array();

    $row[] = uc_date_format(date('Y', $res->date), date('m', $res->date), date('d', $res->date));
    $row[] = $timeslot[$res->sid];
    $row[] = $res->max_limit;
    $row[] = l(t('edit'), 'admin/store/settings/deliverytimeslot/admin/special/'. $res->dsid);
    $rows[] = $row;
  }
  $output .= '<div class="uc-deliverytimeslot-special">';
  if (count($rows)) {
    $header = array(t('Date'), t('Time slot'), t('Max limit'), t('Operations'));
    $output .= theme('table', $header, $rows, array(), t('Special delivery time slot table'));
  }
  else {
    $output .= t('No special date found.') .'&nbsp;';
  }

  // add a special date
  $output .= l(t('Add a special date'), 'admin/store/settings/deliverytimeslot/admin/special/add');
  $output .= '</div>';

  return $output;
}

/**
 * @see uc_deliverytimeslot_admin_view()
 */
function uc_deliverytimeslot_admin_view_filter() {

  $week_days = variable_get('uc_deliverytimeslot_week_days', _uc_deliverytimeslot_week_days());
  if (isset($_SESSION['filter_day'])) {
    $default_day = $_SESSION['filter_day'];
  }
  $form['filter_day'] = array(
    '#type' => 'select',
    '#title' => t('Filter by day'),
    '#options' => $week_days,
    '#default_value' => $default_day,
    '#attributes' => array('onchange' => 'this.form.submit();')
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'View',
    '#attributes' => array('style' => 'display: none;')
  );

  return $form;
}

/**
 * Edit/Add form for delivery time slot and special date
 *
 * @ingroup forms
 * @see uc_deliverytimeslot_admin_edit_form_validate()
 * @see uc_deliverytimeslot_admin_edit_form_submit()
 *
 */
function uc_deliverytimeslot_admin_edit_form($form_state, $type = 'default', $id = 0) {

  $form = array();
  $time_slot = _uc_deliverytimeslot_timeslot();

  // edit mode
  if (is_numeric($id)) {
    switch ($type) {
      case 'default':
        $req = db_fetch_array(db_query("SELECT * FROM {uc_deliverytimeslot_default} WHERE ddid = %d", $id));
        $form['ddid'] = array('#type' => 'value', '#value' => $req['ddid']);
        $day = $req['day'];
        break;
      case 'special':
        $req = db_fetch_array(db_query("SELECT * FROM {uc_deliverytimeslot_special} WHERE dsid = %d", $id));
        $form['dsid'] = array('#type' => 'value', '#value' => $req['dsid']);
        $form['date'] = array('#type' => 'value', '#value' => $req['date']);
        $form['sid'] = array(
          '#type' => 'select',
          '#title' => t('Time slot'),
          '#default_value' => $req['sid'],
          '#options' => $time_slot,
        );
        $day = date(variable_get('uc_date_format_default', 'm/d/Y'), $req['date']);
        break;
    }
    drupal_set_title(t('Edit !type for !day | !timeslot', array('!type' => $type, '!day' => $day, '!timeslot' => $time_slot[$req['sid']])));
    $max = $req ['max_limit'];
    $mode = t('Submit');
  }
  // add mode
  else {
    switch ($type) {
      case 'default':
        drupal_set_title(t('Add a timeslot for !day', array('!day' => arg(7))));
        $form['day'] = array('#type' => 'value', '#value' => arg(7));
        $existing_slot_query = db_query("SELECT sid FROM {uc_deliverytimeslot_default} WHERE day = '%s'", arg(7));
        while ($existing_slot_res = db_fetch_array($existing_slot_query)) {
          unset($time_slot[$existing_slot_res['sid']]);
        }
        if (count($time_slot) > 0) {
          $form['sid'] = array(
            '#type' => 'select',
            '#multiple' => (count($time_slot) > 1) ? TRUE : FALSE,
            '#description' => (count($time_slot) > 1) ? t('Hold Ctrl + click to select multiple values.') : '',
            '#title' => t('Time slot'),
            '#options' => $time_slot,
          );
        }
        break;
      case 'special':
        drupal_set_title(t('Add a special date'));
        $form['date'] = array(
          '#type' => 'date',
          '#title' => t('Special date'),
        );
      $form['sid'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => t('Time slot'),
        '#options' => $time_slot,
      );
        break;
    }
    $mode = t('Add');
  }
  $form['max_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Max limit'),
    '#description' => t('The max limit for this delivery time slot.'),
    '#default_value' => $max ? $max : 5,
    '#size' => 4,
  );
  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => $mode,
  );
  if ($id != 'add') {
    $form['buttons']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
    );
  }
  $form['buttons']['cancel'] = array(
    '#value' => l(t('Cancel'), 'admin/store/settings/deliverytimeslot'),
  );
  return $form;
}

/**
 * @see uc_deliverytimeslot_admin_edit_form()
 */
function uc_deliverytimeslot_admin_edit_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['max_limit']) && !is_numeric($form_state['values']['max_limit'])) {
    form_set_error('max_limit', t('The max limit must be numeric.'));
  }
  // no doublon on special slots
  if ($form_state['values']['op'] == t('Submit')) {
    if (!is_array($form_state['values']['sid']) && isset($form_state['values']['sid'])) {
      $sql = "SELECT count(*) FROM {uc_deliverytimeslot_special} WHERE date= %d AND sid = %d AND dsid <> %d";
      if (db_result(db_query($sql, $form_state['values']['date'], (int)$form_state['values']['sid'], $form_state['values']['dsid']))) {
        form_set_error('sid', t('This time slot for this day already exist. Please edit instead of create.'));
      }
    }
  }
}

/**
 * @see uc_deliverytimeslot_admin_edit_form()
 */
function uc_deliverytimeslot_admin_edit_form_submit($form, &$form_state) {
  switch ($form_state['values']['op']) {
    case t('Delete'):
      // Delete timeslot
      if ($form_state['values']['ddid']) {
        db_query("DELETE FROM {uc_deliverytimeslot_default} WHERE ddid = %d", $form_state['values']['ddid']);
      }
      // Delete special
      if ($form_state['values']['dsid']) {
        db_query("DELETE FROM {uc_deliverytimeslot_special} WHERE dsid = %d", $form_state['values']['dsid']);
      }
      $msg = t('deleted');
      $form_state['redirect'] = 'admin/store/settings/deliverytimeslot';
      break;
    case t('Submit'):
      // Update timeslot
      if ($form_state['values']['ddid']) {
        db_query("UPDATE {uc_deliverytimeslot_default} SET max_limit = %d WHERE ddid = %d", $form_state['values']['max_limit'], $form_state['values']['ddid']);
      }
      // Update special
      if ($form_state['values']['dsid']) {
        db_query("UPDATE {uc_deliverytimeslot_special} SET max_limit = %d, sid = %d WHERE dsid = %d", $form_state['values']['max_limit'], $form_state['values']['sid'], $form_state['values']['dsid']);
      }
      $msg = t('updated');
      $form_state['redirect'] = 'admin/store/settings/deliverytimeslot';
      break;
    case t('Add'):
      $msg = t('created');
      if (isset($form_state['values']['sid'])) {
        $form_sid = $form_state['values']['sid'];
        $max = $form_state['values']['max_limit'];
        if (isset($form_state['values']['day'])) {
          $sql = "INSERT INTO {uc_deliverytimeslot_default} (day, sid, max_limit) VALUES ('%s', %d, %d)";
          $day = $form_state['values']['day'];
        }
        else {
          $day = _uc_deliverytimeslot_date($form_state['values']['date']);
          $sql = "INSERT INTO {uc_deliverytimeslot_special} (date, sid, max_limit) VALUES (%d, %d, %d)";
        }
        foreach ($form_sid AS $sid) {
          db_query($sql, $day, $sid, $max);
        }
      }
      $form_state['redirect'] = 'admin/store/settings/deliverytimeslot';
      break;
  }
  drupal_set_message(t("Delivery successfully !msg.", array('!msg' => $msg)));
}

/**
 * Delivery time slot settings on checkout admin page
 */
function uc_deliverytimeslot_settings_pane() {

  $form = array();
  $form['uc_deliverytimeslot_display_text'] = array(
    '#type' => 'textarea',
    '#title' => t('Description in delivrey checkout pane.'),
    '#default_value' => variable_get('uc_deliverytimeslot_display_text', t('Please specify a date and time of delivery.')),
    '#description' => t('Use this text to give special information about delivrey to your customer.'),
  );
  $form['uc_deliverytimeslot_display_show'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show delivery timeslot by default'),
    '#default_value' => variable_get('uc_deliverytimeslot_display_show', 0),
    '#description' => t('Pane is hidden by default and showing up only when shipping quote is selected, but you can force delivery timeslot visibility.'),
    '#size' => 2,
    '#maxlength' => 2,
  );
  $form['uc_deliverytimeslot_display_days'] = array(
    '#type' => 'textfield',
    '#title' => t('How many days on pane?'),
    '#default_value' => variable_get('uc_deliverytimeslot_display_days', 5),
    '#description' => t('How days in future your customer can select.'),
    '#size' => 2,
    '#maxlength' => 2,
  );
  $form['uc_deliverytimeslot_display_days_future'] = array(
    '#type' => 'textfield',
    '#title' => t('How many days in future should we start on pane?'),
    '#default_value' => variable_get('uc_deliverytimeslot_display_days_future', 0),
    '#description' => t('Select first day your customer can choose, 0 = today, 1 = tomorrow, etc.'),
    '#size' => 2,
    '#maxlength' => 2,
  );
  $form['uc_deliverytimeslot_display_mode'] = array(
    '#type' => 'select',
    '#title' => t('Configure hedear/row of delivery time slot table.'),
    '#default_value' => variable_get('uc_deliverytimeslot_display_mode', 'day'),
    '#description' => t('Choose display of the table, days or time slot on header.'),
    '#options' => array(
                    'day' => t('Day on header row / time slot on left column'),
                    'timeslot' => t('Time slot on header row / days on left column')
                    ),
  );
  $form['settings'] = array(
    '#value' => l(t('Delivery timeslot table settings'), 'admin/store/settings/deliverytimeslot'),
  );
  return $form;
}

/**
 * Generate delivery timeslot settings.
 *
 * @ingroup forms
 * @see uc_deliverytimeslot_settings_validate()
 * @see uc_deliverytimeslot_settings_submit()
 *
 */
function uc_deliverytimeslot_settings() {
  $form = array();
  $form['settings'] = array(
    '#type' => 'fieldset',
    '#description' => t('<b>WARNING</b>: if you change timeslot list when default table already exist, it will change Timeslot title in the same order!'),
    '#title' => t('1. Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['settings']['uc_deliverytimeslot_timeslot'] = array(
    '#type' => 'textarea',
    '#title' => t('Delivery timeslot list'),
    '#default_value' => variable_get('uc_deliverytimeslot_timeslot', _uc_deliverytimeslot_timeslot(FALSE)),
    '#description' => t('Delivery timeslot list, one timeslot per line.'),
    '#required' => TRUE,
  );
  $form['settings']['uc_deliverytimeslot_week_days'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('List of available day for delivery'),
    '#default_value' => variable_get('uc_deliverytimeslot_week_days', _uc_deliverytimeslot_week_days()),
    '#description' => t('Choose wich days will be available for delivery checkout selection.') . t('Hold Ctrl + click to select multiple values.'),
    '#options' => _uc_deliverytimeslot_week_days(),
    '#required' => TRUE,
  );
  $form['settings']['uc_deliverytimeslot_quote'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('Shipping quote selection'),
    '#default_value' => variable_get('uc_deliverytimeslot_quote', array_values(array_flip(uc_quote_shipping_method_options()))),
    '#description' => t('On witch quote delivery timeslot will be available and so required.'),
    '#options' => uc_quote_shipping_method_options(),
    '#required' => TRUE,
  );
  $form['settings']['button']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * @see uc_deliverytimeslot_settings_generate()
 */
function uc_deliverytimeslot_settings_submit($form, &$form_state) {

  if ($form_state['values']['op'] == t('Submit')) {
    variable_set('uc_deliverytimeslot_week_days', $form_state['values']['uc_deliverytimeslot_week_days']);
    variable_set('uc_deliverytimeslot_timeslot', $form_state['values']['uc_deliverytimeslot_timeslot']);
    variable_set('uc_deliverytimeslot_quote', $form_state['values']['uc_deliverytimeslot_quote']);
    drupal_set_message(t("Delivery time slot settings saved."));
  }
}
/**
 * Generate a default timeslot table.
 *
 * @ingroup forms
 * @see uc_deliverytimeslot_settings_generate_validate()
 * @see uc_deliverytimeslot_settings_generate_submit()
 *
 */
function uc_deliverytimeslot_settings_generate() {
  $form = array();
  $form['generate'] = array(
    '#type' => 'fieldset',
    '#title' => t('2. Generation'),
    '#description' => t('<b>WARNING</b>: generate a new table will erase any existing default timeslot table !'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['generate']['uc_deliverytimeslot_week_days_gen'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('List of day for generation'),
    '#description' => t('Choose wich days will be used for generation.') . t('Hold Ctrl + click to select multiple values.'),
    '#options' => variable_get('uc_deliverytimeslot_week_days', _uc_deliverytimeslot_week_days()),
  );
  $form['generate']['uc_deliverytimeslot_timeslot_gen'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('List of time slot for generation'),
    '#description' => t('Choose wich time slot will be used for generation.') . t('Hold Ctrl + click to select multiple values.'),
    '#options' => _uc_deliverytimeslot_timeslot(),
  );
  $form['generate']['max_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Max limit for every time slot on every day'),
    '#default_value' => 5,
    '#size' => 4,
    '#required' => TRUE,
  );
  $form['generate']['button']['submit_warning'] = array(
    '#value' => '<p class="form-required">'. t('<b>WARNING</b>: generate a new table will erase any existing default timeslot table !') .'</p>',
  );
  $form['generate']['button']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Generate timeslot table'),
  );
  return $form;
}

/**
 * @see uc_deliverytimeslot_settings_generate()
 */
function uc_deliverytimeslot_settings_generate_validate($form, &$form_state) {

  if ($form_state['values']['op'] == t('Generate timeslot table')) {
    if (count($form_state['values']['uc_deliverytimeslot_week_days_gen']) == 0) {
      form_set_error('uc_deliverytimeslot_week_days_gen', t('You must choose at last one day.'));
    }
    if (count($form_state['values']['uc_deliverytimeslot_timeslot_gen']) == 0) {
      form_set_error('uc_deliverytimeslot_timeslot_gen', t('You must choose at last one time slot.'));
    }
    if (!empty($form_state['values']['max_limit']) && !is_numeric($form_state['values']['max_limit'])) {
      form_set_error('max_limit', t('The max limit must be numeric.'));
    }
  }
}

/**
 * @see uc_deliverytimeslot_settings_generate()
 */
function uc_deliverytimeslot_settings_generate_submit($form, &$form_state) {

  if ($form_state['values']['op'] == t('Generate timeslot table')) {
    $days = $form_state['values']['uc_deliverytimeslot_week_days_gen'];
    $timeslot = $form_state['values']['uc_deliverytimeslot_timeslot_gen'];
    $max_limit = $form_state['values']['max_limit'];
    db_query("TRUNCATE TABLE {uc_deliverytimeslot_default}");
    foreach ($days as $day) {
      foreach ($timeslot as $sid) {
        db_query("INSERT INTO {uc_deliverytimeslot_default} (day, sid, max_limit) VALUES ('%s', %d, %d)", $day, $sid, $max_limit);
      }
    }
    drupal_set_message(t("Delivery default timeslot table generated."));
  }
}
